import com.wonders.CustomRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        DefaultSecurityManager sc = new DefaultSecurityManager();

        CustomRealm customRealm = new CustomRealm();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashIterations(1024);
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        customRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        sc.setRealm(customRealm);

        SecurityUtils.setSecurityManager(sc);

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("maomao", "123");

        try {
            subject.login(token);
            System.out.println("认证通过：" + subject.isAuthenticated());
        } catch (UnknownAccountException e) {
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
        }

        new Thread(() -> {
            Subject subject1 = SecurityUtils.getSubject();
            System.out.println("认证通过1：" + subject1.isAuthenticated());
            UsernamePasswordToken token1 = new UsernamePasswordToken("maomao", "123");
            subject1.login(token1);
            System.out.println("认证通过1：" + subject1.isAuthenticated());
        }).start();


        if (subject.isAuthenticated()) {
            System.out.println("是否具有admin权限：" + subject.hasRole("admin"));

            boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "operator", "super"));
            System.out.println("是否具有下列权限：");
            for (boolean b : booleans) {
                System.out.println(b);
            }

            System.out.println("是否具有用户创建权限：" + subject.isPermitted("user:create"));
            System.out.println("是否具有用户更新权限：" + subject.isPermitted("user:update"));
            System.out.println("是否具有商品编辑权限：" + subject.isPermitted("product:edit.*"));

        }
    }
}
